// 示例、条文注的公共内容

/**
 * class是否匹配
 * @param {String} string
 * @param {Array} regs 被匹配的字串集合
 * @returns {boolean}
 */
export const classMatch = (string, regs) => {
  const regStr = regs.map((item) => '(' + item + ')').join('|')
  const reg = new RegExp(regStr, 'g')
  return string && string.match(reg) !== null
  // return className && (className.match(/(example)|(itemnote)/g) !== null)
}

/**
 * 获取编号，根据上一行的编号计算+1
 * @param {*} node 当前节点
 * @param {*} classList 需要匹配的class列表
 * @param {*} sortType 返回的顺序类型，1表示返回升序数字123, 否则表示返回字母升序abc
 * @param {String} dataLang 中英文标记
 * @returns
 */
export const getNumber = ({ node, classList, sortType = 1, dataLang = 'zh' }) => {
  const prev = node?.previousElementSibling
  if (!prev) return sortType !== 1 ? 'a' : 1
  const _classMatch = classMatch(prev.className, classList)
  // 上一行的类型和本行必须相同, 中英文属性必须相同
  if (prev && prev.nodeName === node.nodeName && _classMatch && prev.dataset.lang === dataLang) {
    const prevNumber = prev.dataset.number || 0
    if (sortType !== 1) {
      // 脚注的abc到z之后，又以a开始
      let nextCharcode = prevNumber.charCodeAt(0) + 1
      nextCharcode = nextCharcode > 122 ? 97 : nextCharcode
      return String.fromCharCode(nextCharcode)
    }
    return parseInt(prevNumber) + 1
  }
  return sortType !== 1 ? 'a' : 1
}

// 读取下一个字母编号
export function getAlphabetNumber(number) {
  // 脚注的abc到z之后，又以a开始
  let nextCharcode = number.charCodeAt(0) + 1
  nextCharcode = nextCharcode > 122 ? 97 : nextCharcode
  return String.fromCharCode(nextCharcode)
}

// 刷新编号
export const refreshNumber = (data, editor, dataType) => {
  // 重新设置编号，当前节点设置为选择的编号
  const node = editor.selection.getNode()
  if (data.clear) {
    // 清除编号
    if (!node.dataset.restart) {
      return
    }
    const number = getNumber({ node, classList: [dataType] })
    node.setAttribute('data-number', number)
    node.removeAttribute('data-restart')
    // 紧邻编号的示例x也重新设置
    resetNotesSiblingsNumber({ node, editor, classList: [dataType], dataLang: node.dataset.lang })
  } else {
    let restartNumber = parseInt(data.restartNumber)
    editor.dom.setAttribs(node, {
      'data-number': parseInt(restartNumber),
      'data-restart': 1
    })
    // 紧邻编号的示例x也重新设置
    resetNotesSiblingsNumber({ node, editor, classList: [dataType], dataLang: node.dataset.lang })
  }
}

// 重置兄弟节点的连续编号
export const resetNotesSiblingsNumber = ({ node, editor, classList, dataLang, sortType = 1 }) => {
  function walk(next) {
    if (!next) return
    if (
      classList.some((_name) => next?.classList.contains(_name)) &&
      next.dataset.lang === dataLang &&
      !next.dataset.restart
    ) {
      const number = getNumber({
        node: next,
        classList,
        dataLang: next.dataset.lang,
        sortType
      })
      editor.dom.setAttribs(next, {
        'data-number': number
      })
      if (next.nextElementSibling) {
        walk(next.nextElementSibling)
      }
    }
    // if (next?.nextElementSibling) {
    //   walk(next.nextElementSibling)
    // }
  }
  if (node?.nextElementSibling) {
    walk(node.nextElementSibling)
  }
}

// 定义编号的选项
const numberOptions = [...Array(20).keys()].map((i) => ({ value: i + 1 + '', text: i + 1 + '' }))
// 打开重新编号的弹窗
export const openResetNumberDialog = function (editor, dataType) {
  const node = editor.selection.getNode()
  if (node.nodeName !== 'P' || !node.classList?.contains?.(dataType)) {
    return
  }
  const panel = {
    type: 'panel',
    items: [
      {
        type: 'grid',
        columns: 2,
        items: [
          {
            type: 'label',
            label: '清除重置编号',
            items: [
              {
                type: 'checkbox',
                label: '清除',
                name: 'clear'
              }
            ]
          },
          {
            type: 'selectbox',
            label: '定义起始编号',
            name: 'restartNumber',
            items: numberOptions
          }
        ]
      }
    ]
  }
  return editor.windowManager.open({
    title: '重新编号',
    size: 'normal',
    body: panel,
    buttons: [
      {
        type: 'cancel',
        name: 'cancel',
        text: '取消'
      },
      {
        type: 'submit',
        name: 'save',
        text: '确定',
        primary: true
      }
    ],
    initialData: {
      clear: false,
      restartNumber: node.getAttribute('data-number')
    },
    onChange: function (e) {
      // 激活“清除”后，不可选择重新编号
      const _data = e.getData()
      if (_data.clear) {
        e.disable('restartNumber')
      } else {
        e.enable('restartNumber')
      }
    },
    onSubmit: function (e) {
      const data = e.getData()
      refreshNumber(data, editor, dataType)
      e.close()
    }
  })
}

export const integerToAlphabet = (num) => {
  return String.fromCharCode(num + 96)
}
